import { Component, Node, NodeEventType, Rect, Touch, UITransform, Vec2, Vec3, _decorator, v2, v3 } from "cc";

const {ccclass, property} = _decorator;
@ccclass
export default class OutsideClose extends Component {

    @property(Node)
    private bgRect:Node = null!;

    private _locked = true;
    private _callback:(()=>void )|null= null;
    private _bgRectPosition:Vec3 = v3(0, 0, 0);

    public initTouchCallback(cb:()=>void) {
        this._callback = cb;
    }

    onEnable() {
        this.node.on(NodeEventType.TOUCH_END, this.onTouchEnd, this);
    }

    onDisable() {
        this.node.off(NodeEventType.TOUCH_END, this.onTouchEnd, this);
    }

    public setLocked(locked:boolean) {
        this._locked = locked;
    }

    private onTouchEnd(touch:Touch) {
        if (this._locked) return;
        if (!this.checkInside(touch.getUILocation())) {
            this._callback && this._callback();
        }
    }

    private checkInside(touchPos:Vec2):boolean {
        if (!this.bgRect) return true;
        this.bgRect.getPosition(this._bgRectPosition);
        let position = this._bgRectPosition;
        let transform = this.bgRect.getComponent(UITransform)!;
        let lpos = this.bgRect.parent!.getComponent(UITransform)!.convertToNodeSpaceAR(v3(touchPos.x, touchPos.y, 0));
        let rect = new Rect(position.x - transform.width/2, position.y - transform.height/2, transform.width, transform.height);
        return rect.contains(v2(lpos.x, lpos.y));
    }

}
